import os
import subprocess
import time
import csv

SENDDATA_DIR = '../senddata'
CLIENT_BIN = './client'
SERVER_BIN = './server'
CSV_FILE = 'tcp_result.csv'
TCP_PORT = 9002
SERVER_IP = '127.0.0.1'
RECEIVED_DIR = './tcp_receiveddata'
os.makedirs(RECEIVED_DIR, exist_ok=True)

# 获取所有bin文件
bin_files = [f for f in os.listdir(SENDDATA_DIR) if f.endswith('.bin')]
bin_files.sort()

results = []

for fname in bin_files:
    send_path = os.path.join(SENDDATA_DIR, fname)
    recv_path = os.path.join(RECEIVED_DIR, fname.replace('.bin', '_recv.bin'))
    # 启动client（先启动接收端）
    client_cmd = [CLIENT_BIN, 'tcp', str(TCP_PORT), recv_path]
    client_proc = subprocess.Popen(client_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    time.sleep(0.2)  # 确保client已监听
    # 启动server
    server_cmd = [SERVER_BIN, send_path, 'tcp', SERVER_IP, str(TCP_PORT)]
    start = time.time()
    server_out = subprocess.run(server_cmd, capture_output=True, text=True)
    end = time.time()
    # 等待client结束
    client_stdout, client_stderr = client_proc.communicate(timeout=60)
    print(client_stdout)
    # 解析server输出
    elapsed = None
    speed = None
    for line in server_out.stdout.splitlines():
        if 'Elapsed time:' in line:
            elapsed = float(line.split('Elapsed time:')[1].split('s')[0].strip())
        if 'Speed:' in line:
            speed = float(line.split('Speed:')[1].split('MB/s')[0].strip())
    # 解析client输出
    md5_result = None
    for line in client_stdout.splitlines():
        if 'MD5 check:' in line:
            md5_result = line.split('MD5 check:')[1].strip()
    # 文件大小
    fsize = os.path.getsize(send_path)
    results.append({
        'file': fname,
        'size': fsize,
        'elapsed': elapsed,
        'speed_MBps': speed,
        'md5_check': md5_result
    })
    print(f"{fname}: size={fsize}, elapsed={elapsed}, speed={speed}, md5_check={md5_result}")

# 写入csv
with open(CSV_FILE, 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['file', 'size', 'elapsed', 'speed_MBps', 'md5_check'])
    writer.writeheader()
    for row in results:
        writer.writerow(row)
print(f"Results saved to {CSV_FILE}") 